package star.cloud.asme.system.user.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;
import star.cloud.asme.base.utils.ObjectsUtil;
import star.cloud.asme.system.user.User;
import star.cloud.asme.system.user.UserMapper;

import java.util.Collection;
import java.util.UUID;

@Configuration
@RequiredArgsConstructor
public class UserImportListener implements ReadListener<UserDTO> {
    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;

    @Override
    public void invoke(UserDTO data, AnalysisContext context) {
        saveUser(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }


    private void saveUser(UserDTO userImport) {
        User user = User.builder()//
                .username(userImport.getUsername())//
                .name(userImport.getName())//
                .workNo(userImport.getWorkNo())//
                .email(userImport.getEmail())//
                .idCard(userImport.getIdCard())//
                .phone(userImport.getPhone())
                //
                .build();
        System.out.println(user);
        Collection<User> usersSelected = userMapper.selectListByUsernameOrWorkNoOrEmailOrPhoneOrIdCard(user);
        if (usersSelected.isEmpty()) {
            user.setHeadImageUuid(UUID.randomUUID().toString());
            if (user.getPassword() == null) {
                user.setPassword(passwordEncoder.encode("admin12345678"));
            }

            if (ObjectsUtil.isNull(user.getDepartment())) {
                user.setDepartmentId(0L);
            }

            try {
                System.out.println(user);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }

    }

}